<template>
    <van-nav-bar :title="title" left-text="返回" left-arrow @click-left="back" />
    <div v-if="!loading && !errorState">

        <!-- 菜谱步骤 -->
        <div class="step">
            <h2>步骤</h2>
            <pre>{{ step }}</pre>
        </div>
        <!-- 所需食材 -->
        <div class="food-list">
            <h2>所需食材</h2>
            <pre class="mermaid">{{ materials }}</pre>
        </div>
        <VerticalSpace size="55px" />

        <!-- 加入菜篮 -->
        <div class="btn-group" v-if="!loading">
            <div class="star-container" @click="collect">
                <van-icon name="star-o" class="star-btn" size="18" v-show="!collectState" />
                <van-icon name="star" color="rgb(243, 35, 41)" class="star-btn" size="18" v-show="collectState" />
                <span>收藏</span>
            </div>
            <div class="basket-container" @click="goBasket">
                <van-icon name="cart-o" class="star-btn" :badge="basketBadge" size="18" />
                <span>菜篮</span>
            </div>
            <van-button round type="success" class="join-btn" color="linear-gradient(to right, #ff6034, #ee0a24)"
                @click="join">加入菜篮</van-button>
        </div>

    </div>


    <!-- 显示加载中 -->
    <Loading v-if="loading" />

    <!-- 显示空状态 -->
    <van-empty image="error" description="菜谱未找到" v-if="!loading && errorState" />

</template>

<script setup lang="ts">
import req from '@/utils/requests'
import { useBasketStore, type Cook } from '@/stores/basket.ts'
import VerticalSpace from '@/components/VerticalSpace.vue'


// 路由实例
const router = useRouter()

const route = useRoute()

// 是否正在加载
const loading = ref(true)
// 菜谱异常
const errorState = ref(false)
// 收藏
const collectState = ref(false)

// 页面标题
const title = ref('菜谱详情')

const step = ref('')

// 食材列表
const materials = ref('')

// 菜谱
let cook: Cook

const renderContent = (content: string) => {
    // 分割文本为步骤部分和所需素材部分
    const parts = content.split(/\n\s*\n/);
    let steps = '';
    let ingredients = '';

    // 查找步骤部分的结束位置
    let stepsEndIndex = -1;
    for (let i = 0; i < parts.length; i++) {
        if (parts[i].includes('所需素材')) {
            stepsEndIndex = i;
            break;
        }
    }

    if (stepsEndIndex === -1) {
        // 如果没有找到明确的分隔，假设第一部分是步骤
        steps = parts[0].trim();
        ingredients = parts.slice(1).join('\n').trim();
    } else {
        // 如果有明确的分隔
        steps = parts.slice(1, stepsEndIndex).join('\n').trim();
        ingredients = parts.slice(stepsEndIndex + 1).join('\n').trim();
    }
    step.value = steps
    materials.value = ingredients
    console.log(`步骤: ${step.value}`)
    cook.content = ingredients
}

onMounted(async () => {
    // 获取组件传递过来的参数
    try {
        const param = route.params
        const cookId = param.cookId
        console.log(`cookId: ${cookId}`)
        cook = await req.get(`/api/cook/${cookId}`)
        console.log(`打印日志`)
        title.value = cook.name
        renderContent(cook.content)
    } catch (error: any) {
        console.error(`初始化异常`, error)
        errorState.value = true
    } finally {
        loading.value = false
    }
})

// 菜篮
const basketStore = useBasketStore()

// 菜篮的徽标
const basketBadge = computed(() => {
    return basketStore.size()
})

const collect = () => {
    const params = route.params
    console.log(`收藏: ${params.cookId}`)
    collectState.value = !collectState.value
}

// 去菜篮
const goBasket = () => {
    router.push('/basket')
}

// 加入菜篮
const join = () => {
    console.log('加入菜篮')
    basketStore.add(cook)
}

function back(): void {
    router.back()
}

</script>

<style scoped>
.step {
    padding-left: 15px;
    padding-top: 10px;
    padding-right: 15px;
    padding-bottom: 10px;
}

.food-list {
    padding-left: 10px;
    padding-top: 10px;
    padding-right: 10px;
    padding-bottom: 10px;
}

pre {
    white-space: pre-wrap;
    white-space: -moz-pre-wrap;
    white-space: -pre-wrap;
    white-space: -o-pre-wrap;
    word-wrap: break-word;
    font-family: var(--van-base-font);
    font-size: 16px;
    line-height: 32px;
}


h2 {
    margin-top: 10px;
    margin-bottom: 10px;
    font-weight: bold;
}

.btn-group {
    position: fixed;
    bottom: 0;
    height: var(--van-tabbar-height);
    width: 100%;
    background: var(--van-tabbar-background);
    z-index: var(--van-tabbar-z-index);
    box-sizing: content-box;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .star-container {
        display: flex;
        flex-direction: column;
        align-items: center;
        flex: 1;
        font-size: 12px;
    }

    .join-btn {
        flex: 3;
        margin-right: 10px;
        height: 30px;
    }

    :deep(.van-badge) {
        margin-top: var(--van-padding-base);
    }

}

.basket-container {
    display: flex;
    flex-direction: column;
    flex: 1;
    font-size: 12px;
    justify-content: center;
    align-items: center;
}

.btn-group:after {
    /* border-width: var(--van-border-width) 0; */
    content: " ";
    position: absolute;
    box-sizing: border-box;
    pointer-events: none;
    border: 1px solid var(--van-border-color);
    top: -50%;
    right: -50%;
    bottom: -50%;
    left: -50%;
    transform: scale(.5);
}
</style>
